﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using DAL.ZipCodeServiceReference;
using DAL.ConfirmeServiceReference;
using COMMON;
using VO;


namespace DAL
{
    public class ContatoServicoDAL
    {

        #region LoginZipCode
        internal Retorno<string> LoginZipCode()
        {
            var retorno = new Retorno<string>();
            
            var service = new PesquisaSoapClient();
            var key = service.Login(Configuracao.UserZipCode(), Configuracao.PassZipCode());
            if (key.Split(' ').Length <= 1)
            {
                retorno.Key = key;
                retorno.Error = Enumerator.Error.Success;
                retorno.Message = "OK";
            }
            else
            {
                retorno.Error = Enumerator.Error.Failed;
                retorno.Message = key;
            }
            
            return retorno;
        }
        #endregion

        #region ConsultaContatoZipCode
        public IList<ContatoCliente> ConsultaContatoZipCode(string cpf, int idCliente, int idUsuario)
        {
            var list = new List<ContatoCliente>();
            var retorno = LoginZipCode();
            var objLog = new LogConsultaWebService
                             {
                                 strCPF = cpf,DataConsulta = DateTime.Now,WebService = Enumerator.ConsultaWebService.ZipCode.ToString(),IdUsuario = idUsuario
                             };

            if (retorno.Error == Enumerator.Error.Success)
            {
                var key = retorno.Key;
                var service = new PesquisaSoapClient();
                var parametro = string.Format("<consulta nome=\"Preview CPF\"><criterio><campo nome=\"NR_CPF\">{0}</campo></criterio></consulta>", cpf);
                var consulta = service.ConsultaZipCode(parametro, key);
                objLog.strXml = consulta;
                InsertTelefone(objLog);
                if (consulta.Length > 13)
                {
                    var xml = new XmlDocument();
                    xml.LoadXml(consulta);

                    var xnList = xml.SelectNodes("/Root/Resultado/row/Telefones/row");

                    if (xnList != null)
                        list.AddRange(from XmlNode xn in xnList
                                      select xn["DDD"].InnerText + xn["Telefone"].InnerText
                                      into telefone select new ContatoCliente
                                                               {
                                                                   Telefone = telefone.Replace("-", ""), idCliente = idCliente, fgAtivo = true, TipoTelefone = string.Empty
                                                               });
                }
                else
                {
                    retorno.Error = Enumerator.Error.NoRegistry;
                    retorno.Message = "Sem dados";
                }
                
            }
            return list;
        }
        #endregion

        #region ConsultaContatoConfirme
        public IList<ContatoCliente> ConsultaContatoConfirme(string cpf, int idCliente, int idUsuario)
        {
            var list = new List<ContatoCliente>();
            var service = new ConsultaClient();
           
            var consulta = service.Cpfcnpj(Configuracao.UserConfirme(), Configuracao.PassConfirme(), Configuracao.SiglaConfirme(), cpf);
            var objLog = new LogConsultaWebService
            {
                strCPF = cpf,
                DataConsulta = DateTime.Now,
                WebService = Enumerator.ConsultaWebService.ConfirmeOnLine.ToString(),
                IdUsuario = idUsuario,
                strXml = consulta
            };
            InsertTelefone(objLog);
            if (consulta.Length > 13)
            {
                var xml = new XmlDocument();
                xml.LoadXml(consulta);

                var root = xml.DocumentElement;
                if (root != null)
                {
                    var xnList = root.GetElementsByTagName("TELEFONE");
                    list.AddRange(from XmlNode xn in xnList
                                  where xn.FirstChild.Value != null
                                  select new ContatoCliente
                                             {
                                                 Telefone = xn.FirstChild.Value, idCliente = idCliente, fgAtivo = true, TipoTelefone = string.Empty
                                             });
                }
            }
            return list;
        }
        #endregion
        #region InsertTelefone
        public static Retorno<LogConsultaWebService> InsertTelefone(LogConsultaWebService obj)
        {
            var objReturn = new Retorno<LogConsultaWebService>();
            try
            {
                //Insere Log
                //var list = SelectTelefone(obj.IdUsuario, obj.WebService);
                new LogConsultaWebServiceDAL().Insert(obj);
                objReturn.Error = Enumerator.Error.Success;
                objReturn.Message = "OK";
            }
            catch (Exception ex)
            {
                objReturn.Error = Enumerator.Error.Failed;
                objReturn.Message = ex.Message;
            }
            return objReturn;
        }
       
        #endregion

    }
}